$(function () {
	var searchParam="";
	var urlParam=location.search;
	if(urlParam){
		searchParam=urlParam;
	}
	
    $("#companyInfoGrid").Grid({
        url: '../org/info/list'+searchParam,
        colModel: [
			{label: 'id', name: 'id', index: 'id', key: true, hidden: true},
			{label: '公司简称', name: 'name', index: 'name', width: 80},
			{label: '公司全名', name: 'allName', index: 'all_name', width: 80},
			{label: '联系人', name: 'attn', index: 'attn', width: 80},
			{label: '联系人电话', name: 'phone', index: 'phone', width: 80},
			{label: '公司电话', name: 'tel', index: 'tel', width: 80},
			{label: '申请时间', name: 'createTime', index: 'createTime', width: 80},
			{label: '状态', name: 'status', index: 'status', width: 80,
				formatter: function (value) {
					var result="";
					switch (value) {
						case 0:result='<span class="label label-danger">冻结</span>';break;
						case 1:result='<span class="label label-success">正常</span>';break;
						case 2:result='<span class="label label-info">待审核</span>';break;
						case 3:result='<span class="label label-danger">审核未通过</span>';break;
						default:result='<span class="label label-success">正常</span>';break;
					}
					return result;
				}
			}]
    });
    vm.getEreaDict(1,1);
});

var validatePhone=function(rule, value, callback){
	if(vm.orgCompanyInfo.id){
		callback();return;
	}
	var myPhoneReg=/^[1][3,4,5,6,7,8][0-9]{9}$/;
	if (!myPhoneReg.test(value)) {
		callback(new Error('手机号格式不正确'));
    } else {
    	var vPhoneUrl="../org/employeeInfo/queryAllPerson?phone="+value;
    	Ajax.request({
			url: vPhoneUrl,
			type: "POST",
			contentType: "application/json",
			successCallback: function (r) {
				if(r.code==0){
					if(r.list.length>0){
						var personInfo=r.list[0];
						if(vm.orgCompanyInfo.attn&&vm.orgCompanyInfo.phone
								&&vm.orgCompanyInfo.attn==personInfo.name
								&&vm.orgCompanyInfo.phone==personInfo.phone){
							callback();return;
						}else{
							callback(new Error('手机号已经被使用'));return;
						}
					}else{
						callback();
					}
				}else{
					callback();
				}
			}
		});
    }
};

var vm = new Vue({
	el: '#companyInfo',
	data: {
        showList: true,
        showAuditDetail: false,
        title: null,
        uploadLicenseList:[],
        uploadLogoList:[],
        uploadIdcardPositiveList:[],
        uploadIdcardReverseList:[],
		orgCompanyInfo: {},
		areaClear:false,
		provinceList:[],
		cityList:[],
		areaList:[],
		ruleValidate: {
			name: [
				{required: true, message: '名称不能为空', trigger: 'blur'}
			],
			serialNo: [
			       {required: true, message: '公司编号不能为空', trigger: 'blur'}
			],
			attn: [
		       {required: true, message: '联系人不能为空', trigger: 'blur'}
		    ],
			phone: [
			    {required: true, message: '联系人电话不能为空', trigger: 'blur'},
			    {validator: validatePhone, trigger: 'change'}
			],
			logo:[
                {required: true, message: '请上传公司logo', trigger: 'blur'}
			]
		},
		q: {
		    name: '',legal:'',attn:''
		}
	},
	methods: {
		handleBrandRemove:function(event,name){
			var brandId=name;
			var brandSelectedList=vm.orgCompanyInfo.brandList;
			if(brandSelectedList&&brandSelectedList.length>0){
				for (var i = 0; i < brandSelectedList.length; i++) {
    				if(brandId==brandSelectedList[i].id){
    					brandSelectedList.splice(i,1);break;
    				}
				}
				vm.orgCompanyInfo.brandList=brandSelectedList;
			}
		},
		selectBrandAll:function(){
			openWindow({
            	type: 2,
                title: "选择车辆品牌",
                area: ['80%', '60%'],
                content: ['../product/carbrandSelect.html'],
                btn: ['确定', '取消'],
                btn1: function (index,layero) {
                	var selectRowList = window[layero.find('iframe')[0]['name']].getSelectedRowsData('#carbrandSelectGrid');
                	if(selectRowList&&selectRowList.length>0){
                		if(!vm.orgCompanyInfo.brandList){
            				vm.orgCompanyInfo.brandList=[];
            			}
                		for (var i = 0; i < selectRowList.length; i++) {
                			var addSelected=true;
                			for (var j = 0; j < vm.orgCompanyInfo.brandList.length; j++) {
                				if(selectRowList[i].id==vm.orgCompanyInfo.brandList[j].id){
                					addSelected=false;
                				}
							}
                			if(addSelected){
                				vm.orgCompanyInfo.brandList.push(selectRowList[i]);
                			}
                		}
                	}
                    layer.close(index);
                }
            });
		},
		selectProvince:function(val){
			var province_name='';
			for(var i=0;i<vm.provinceList.length;i++){
				if(val==vm.provinceList[i].id){
					province_name=vm.provinceList[i].name;
					vm.orgCompanyInfo.provinceName=province_name;
				}
			}
			vm.getEreaDict(val,2);
			if(!vm.areaClear){
				vm.areaClear=false;
			}else{
				this.$refs.companyInfoArearesetSelect.clearSingleSelect();
			}
		},
		selectCity:function(val){
			var city_name='';
			for(var i=0;i<vm.cityList.length;i++){
				if(val==vm.cityList[i].id){
					city_name=vm.cityList[i].name;
					vm.orgCompanyInfo.cityName=city_name;
				}
			}
			vm.getEreaDict(val,3);
		},
		selectArea:function(val){
			var area_name='';
			for(var i=0;i<vm.areaList.length;i++){
				if(val==vm.areaList[i].id){
					area_name=vm.areaList[i].name;
					vm.orgCompanyInfo.areaName=area_name;
				}
			}
		},
		selectCompanyEmployee:function(){
			openWindow({
            	type: 2,
                title: "选择人员",
                area: ['60%', '80%'],
                content: ['../org/employeeInfoSelect.html?companyId='+vm.orgCompanyInfo.id],
                btn: ['确定', '取消'],
                btn1: function (index,layero) {
                	var selectRowData = window[layero.find('iframe')[0]['name']].getSelectedRowData('#employeeInfoGrid');
                	vm.orgCompanyInfo.attn=selectRowData.name;
                	vm.orgCompanyInfo.phone=selectRowData.phone;
                	vm.orgCompanyInfo.personId=selectRowData.personId;
                    layer.close(index);
                }
            });
		},
		query: function () {
			vm.reload();
		},
		add: function () {
			vm.uploadLicenseList=[];
			vm.uploadLogoList=[];
			vm.uploadIdcardPositiveList=[];
			vm.uploadIdcardReverseList=[];
			vm.showList = false;
			vm.showAuditDetail=false;
			vm.title = "新增";
			vm.orgCompanyInfo = {type:1,brandList:[]};
		},
		update: function (event) {
			vm.uploadLicenseList=[];
			vm.uploadLogoList=[];
			vm.uploadIdcardPositiveList=[];
			vm.uploadIdcardReverseList=[];
            var id = getSelectedRow("#companyInfoGrid");
			if (id == null) {
				return;
			}
			vm.showList = false;
			vm.showAuditDetail=false;
            vm.title = "修改";

            vm.getInfo(id);
		},
		freeze:function(){
			var ids = getSelectedRows("#companyInfoGrid");
			if (ids == null){
				return;
			}
			confirm('确定要冻结选中的公司？', function () {
                Ajax.request({
				    url: "../org/info/freeze",
                    params: JSON.stringify(ids),
                    type: "POST",
				    contentType: "application/json",
                    successCallback: function () {
                        alert('操作成功', function (index) {
                            vm.reload();
                        });
					}
				});
			});
		},
		audit:function(){
			vm.uploadLicenseList=[];
			vm.uploadLogoList=[];
			vm.uploadIdcardPositiveList=[];
			vm.uploadIdcardReverseList=[];
            var id = getSelectedRow("#companyInfoGrid");
			if (id == null) {
				return;
			}
			vm.showList = false;
			vm.showAuditDetail=true;
            vm.title = "审核信息";

            vm.getInfo(id);
		},
		getEreaDict: function (pid,level) {
        	//加载部门树
			if(pid){
				if(pid==1) pid=0;
				Ajax.request({
					url: "../sys/dict/area?pid="+pid,
					async: true,
					successCallback: function (r) {
						if(level==1){
							vm.provinceList=r.list;
						}else if(level==2){
							vm.cityList=r.list;
						}else if(level==3){
							vm.areaList=r.list;
							if(vm.areaList.length<=0){
								console.log("vm.areaList is 0;");
							}
						}
					}
				});
			}
        },
		saveOrUpdate: function (event) {
            var url = vm.orgCompanyInfo.id == null ? "../org/info/save" : "../org/info/update";
            if(!vm.orgCompanyInfo.areaId){
            	vm.orgCompanyInfo.areaName=null;
            }
            Ajax.request({
			    url: url,
                params: JSON.stringify(vm.orgCompanyInfo),
                type: "POST",
			    contentType: "application/json",
                successCallback: function (r) {
                    alert('操作成功', function (index) {
                        vm.reload();
                    });
                }
			});
		},
		auditYes: function () {
			if(vm.orgCompanyInfo.id){
				confirm('确定要审核通过选中的公司？', function () {
					Ajax.request({
						url: "../org/info/auditYes",
						params: JSON.stringify([vm.orgCompanyInfo.id]),
						type: "POST",
						contentType: "application/json",
						successCallback: function () {
							alert('操作成功', function (index) {
								vm.reload();
							});
						}
					});
				});
			}
		},
		auditNo: function () {
			if(vm.orgCompanyInfo.id){
				confirm('确定要审核通过选中的公司？', function () {
					Ajax.request({
						url: "../org/info/auditNo",
						params: JSON.stringify([vm.orgCompanyInfo.id]),
						type: "POST",
						contentType: "application/json",
						successCallback: function () {
							alert('操作成功', function (index) {
								vm.reload();
							});
						}
					});
				});
			}
		},
		del: function (event) {
            var ids = getSelectedRows("#companyInfoGrid");
			if (ids == null){
				return;
			}

			confirm('确定要删除选中的记录？', function () {
                Ajax.request({
				    url: "../org/info/delete",
                    params: JSON.stringify(ids),
                    type: "POST",
				    contentType: "application/json",
                    successCallback: function () {
                        alert('操作成功', function (index) {
                            vm.reload();
                        });
					}
				});
			});
		},
		getInfo: function(id){
            Ajax.request({
                url: "../org/info/info/"+id,
                async: true,
                successCallback: function (r) {
                	vm.areaClear=true;
                    vm.orgCompanyInfo = r.orgCompanyInfo;
                    if(vm.orgCompanyInfo.license){
                    	vm.uploadLicenseList.push({name:vm.orgCompanyInfo.license.substr(vm.orgCompanyInfo.license.lastIndexOf("/")),url:vm.orgCompanyInfo.license,status:'finished'});
                    }
                    if(vm.orgCompanyInfo.logo){
                    	vm.uploadLogoList.push({name:vm.orgCompanyInfo.logo.substr(vm.orgCompanyInfo.logo.lastIndexOf("/")),url:vm.orgCompanyInfo.logo,status:'finished'});
                    }
                    if(vm.orgCompanyInfo.idcardPositive){
                    	vm.uploadIdcardPositiveList.push({name:vm.orgCompanyInfo.idcardPositive.substr(vm.orgCompanyInfo.idcardPositive.lastIndexOf("/")),url:vm.orgCompanyInfo.idcardPositive,status:'finished'});
                    }
                    if(vm.orgCompanyInfo.idcardReverse){
                    	vm.uploadIdcardReverseList.push({name:vm.orgCompanyInfo.idcardReverse.substr(vm.orgCompanyInfo.idcardReverse.lastIndexOf("/")),url:vm.orgCompanyInfo.idcardReverse,status:'finished'});
                    }
                }
            });
		},
		reload: function (event) {
			vm.showList = true;
			vm.showAuditDetail = false;
            var page = $("#companyInfoGrid").jqGrid('getGridParam', 'page');
			$("#companyInfoGrid").jqGrid('setGridParam', {
                postData: {'name': vm.q.name,'legal':vm.q.legal,'attn':vm.q.attn},
                page: 1
            }).trigger("reloadGrid");
//            vm.handleReset('formValidate');
		},
        reloadSearch: function() {
            vm.q = {
                name: '',legal:'',attn:''
            };
            vm.reload();
        },
        handleSubmit: function (name) {
            handleSubmitValidate(this, name, function () {
                vm.saveOrUpdate()
            });
        },
        handleReset: function (name) {
            handleResetForm(this, name);
        },
        handleView:function(file){
        	openWindow({
            	type: 2,
                title: "图片显示",
                area: ['80%', '60%'],
                content: [file.url],
                btn: ['确定', '取消'],
                btn1: function (index,layero) {
                    layer.close(index);
                }
            });
        },
        handleRemove:function(type){
        	switch (type) {
				case "license":vm.uploadLicenseList=[];break;
				case "logo":vm.uploadLogoList=[];break;
				case "idcardPositive":vm.uploadIdcardPositiveList=[];break;
				case "idcardReverse":vm.uploadIdcardReverseList=[];break;
				default:break;
			}
        },
        handleSuccessLogo:function(res, file){
        	vm.uploadLogoList.push({name:res.filename,url:res.link+res.filename,status:'finished'});
        	vm.orgCompanyInfo.logo=res.link+res.filename;
        },
        handleSuccessLicense:function(res, file){
        	vm.uploadLicenseList.push({name:res.filename,url:res.link+res.filename,status:'finished'});
        	vm.orgCompanyInfo.license=res.link+res.filename;
        },
        handleSuccessIdcardPositive:function(res, file){
        	vm.uploadIdcardPositiveList.push({name:res.filename,url:res.link+res.filename,status:'finished'});
        	vm.orgCompanyInfo.idcardPositive=res.link+res.filename;
        },
        handleSuccessIdcardReverse:function(res, file){
        	vm.uploadIdcardReverseList.push({name:res.filename,url:res.link+res.filename,status:'finished'});
        	vm.orgCompanyInfo.idcardReverse=res.link+res.filename;
        },
        handleImgFormatError:function(file){
        	alert('图片格式错误！支持图片格式为:jpg,png,jpeg!');
        },
        handleImgMaxSize:function(file){
        	alert('图片最大大小为4M!');
        },
        handleLogoImgBeforeUpload:function(){
        	var check = vm.uploadLogoList.length < 1;
            if (!check) {
            	alert('首先删除原来的图片!');
            }
            return check;
        },
        handleLicenseImgBeforeUpload:function(){
        	var check = vm.uploadLicenseList.length < 1;
        	if (!check) {
        		alert('首先删除原来的图片!');
        	}
        	return check;
        },
        handleIdcardPositiveImgBeforeUpload:function(){
        	var check = vm.uploadIdcardPositiveList.length < 1;
        	if (!check) {
        		alert('首先删除原来的图片!');
        	}
        	return check;
        },
        handleIdcardReverseImgBeforeUpload:function(){
        	var check = vm.uploadIdcardReverseList.length < 1;
        	if (!check) {
        		alert('首先删除原来的图片!');
        	}
        	return check;
        }
	}
});